package com.huluobo.a2202kotlindouyindemo.live

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2202kotlindouyindemo.R
import com.huluobo.a2202kotlindouyindemo.adapter.GiftAdapter
import com.huluobo.a2202kotlindouyindemo.adapter.MessageAdapter
import com.huluobo.a2202kotlindouyindemo.databinding.ActivityLiveBinding
import com.huluobo.a2202kotlindouyindemo.pay.PayActivity
import com.huluobo.a2202kotlindouyindemo.shop.ShopActivity
import com.huluobo.a2202kotlindouyindemo.utils.ImageUtils
import com.huluobo.base.bean.GiftBean
import com.huluobo.base.bean.MessageEntity
import com.huluobo.base.bean.Money
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMActivity
import com.hyphenate.EMCallBack
import com.hyphenate.EMChatRoomChangeListener
import com.hyphenate.EMMessageListener
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMChatRoom
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.Danmaku
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser

//   val videoBean: VideoBean = intent.getSerializableExtra("videoBean") as VideoBean
//        Log.i("TagA", "videoBean:${videoBean.caption}")
class LiveActivity : BaseMVVMActivity<ActivityLiveBinding>() {
    private lateinit var videoBean: VideoBean
    private lateinit var viewModel: LiveViewModel
    private lateinit var giftAdapter: GiftAdapter
    private val giftList = mutableListOf<GiftBean>()
    private lateinit var giftBean: GiftBean
    private lateinit var money: Money
    private lateinit var messageAdapter: MessageAdapter
    private val messageList = mutableListOf<MessageEntity>()
    override fun initData() {
        viewModel = ViewModelProvider(this)[LiveViewModel::class.java]

        viewModel.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                dataBinding.liveFollowBtn.text = "已关注"
                dataBinding.liveFollowBtn.setBackgroundResource(R.drawable.shape_alpha_black)
                videoBean.guanzhu = 1
            }
        }

        viewModel.followAuthFailed.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.noFollowAuthSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                dataBinding.liveFollowBtn.text = "关注"
                dataBinding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red)
                videoBean.guanzhu = 0
            }
        }

        viewModel.noFollowAuthFailed.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.getGiftListSuccess.observe(this) {
            if (it.code == 200) {
                giftList.clear()
                giftList.addAll(it.data)
                giftAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getGiftListFailed.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.queryUserMoneySuccess.observe(this) {
            money = it
            dataBinding.liveUserMoneyTv.text = "余额:${money.money}抖币"
        }

        viewModel.queryUserMoneyFailed.observe(this) {
            Log.i("TagA", "查询用户余额失败:$it")
        }

    }

    override fun initView() {
        videoBean = intent.getSerializableExtra("videoBean") as VideoBean

        dataBinding.liveGsyPlayer.backButton.visibility = View.GONE
        dataBinding.liveGsyPlayer.setUp(videoBean.videopath, true, "")
//        dataBinding.liveGsyPlayer.startPlayLogic()

        //头像
        ImageUtils.loadCircleImage(this, videoBean.headpath, dataBinding.liveUserIconIv)
        //作者
        dataBinding.liveUsernameTv.text = videoBean.authname
        //关注状态
        dataBinding.liveFollowBtn.text = if (videoBean.guanzhu == 0) "关注" else "已关注"
        dataBinding.liveFollowBtn.setBackgroundResource(if (videoBean.guanzhu == 0) R.drawable.shape_red else R.drawable.shape_alpha_black)
        //喜欢数量
        dataBinding.liveLikeCountTv.text = "${videoBean.like_count}人喜欢"
        //关注状态的点击事件
        dataBinding.liveFollowBtn.setOnClickListener {
            if (videoBean.guanzhu == 0) {
                //触发关注接口
                viewModel.followAuth(videoBean.authname)
            } else {
                //触发取消关注接口
                viewModel.noFollowAuth(videoBean.authname)
            }
        }

        val resIds = arrayOf(
            R.drawable.ic_favorite_0,
            R.drawable.ic_favorite_1,
            R.drawable.ic_favorite_2,
            R.drawable.ic_favorite_3,
            R.drawable.ic_favorite_4,
            R.drawable.ic_favorite_5,
            R.drawable.ic_favorite_4,
            R.drawable.ic_favorite_3,
            R.drawable.ic_favorite_2,
            R.drawable.ic_favorite_1,
            R.drawable.ic_favorite_0,
        )
        dataBinding.liveLikeView.setResIds(resIds)

        dataBinding.liveLikeIv.setOnClickListener {
            dataBinding.liveLikeView.addFavor()
        }

        dataBinding.liveDanmuIv.setOnClickListener {
            dataBinding.liveDanmuLayoutLl.visibility = View.VISIBLE
        }

        initDanmuView()

        dataBinding.liveDanmuSendIv.setOnClickListener {
            sendDammu()
        }

        //初始化礼物列表
        dataBinding.liveGiftListRv.layoutManager = GridLayoutManager(this, 5)
        giftAdapter = GiftAdapter(giftList)
        dataBinding.liveGiftListRv.adapter = giftAdapter

        giftAdapter.setOnItemClickListener { _, _, position ->
            giftBean = giftList[position]
            ImageUtils.loadImage(this, giftBean.giftpath, dataBinding.liveGiftSelectIv)
            dataBinding.liveGiftNameTv.text = giftBean.giftname
        }

        dataBinding.liveGiftSendBtn.setOnClickListener {
            sendGift();
        }


        dataBinding.liveGiftIv.setOnClickListener {
            dataBinding.liveGiftLayoutCl.visibility = View.VISIBLE
            viewModel.getGiftList()
            viewModel.queryUserMoney(SPUtils.getInstance().getString(Const.PARAM_USERNAME))
        }

        dataBinding.liveCloseTv.setOnClickListener {
            dataBinding.liveGiftLayoutCl.visibility = View.GONE
        }

        dataBinding.livePayBtn.setOnClickListener {
            val intent = Intent(this, PayActivity::class.java)
            startActivity(intent)
        }

        dataBinding.liveInputTv.setOnClickListener {
            dataBinding.liveChatRoomLayoutLl.visibility = View.VISIBLE
        }

        //初始化聊天室列表
        messageAdapter = MessageAdapter(messageList)
        dataBinding.liveChatRoomRv.layoutManager = LinearLayoutManager(this)
        dataBinding.liveChatRoomRv.adapter = messageAdapter

        initChatRoom()

        //发送消息点击事件
        dataBinding.liveChatRoomSendIv.setOnClickListener {
            //聊天室假效果
//            val messageEntity = MessageEntity(
//                SPUtils.getInstance().getString(Const.PARAM_USERNAME),
//                dataBinding.liveChatRoomInputEt.text.toString()
//            )
//            messageList.add(messageEntity)
//            messageAdapter.notifyDataSetChanged()
//            dataBinding.liveChatRoomRv.scrollToPosition(messageList.size - 1)
//            dataBinding.liveChatRoomInputEt.text.clear()
//            dataBinding.liveChatRoomLayoutLl.visibility = View.GONE
            val emMessage =
                EMMessage.createTextSendMessage(
                    dataBinding.liveChatRoomInputEt.text.toString(),
                    Const.CHAT_ROOM_ID
                )//构建一条EMMessage
            emMessage.chatType = EMMessage.ChatType.ChatRoom//设置消息类型为聊天室消息
            emMessage.body = EMTextMessageBody(dataBinding.liveChatRoomInputEt.text.toString())//构建消息体
            EMClient.getInstance().chatManager().sendMessage(emMessage)//发送消息

            emMessage.setMessageStatusCallback(object : EMCallBack {
                override fun onSuccess() {
                    //发送消息成功
                    runOnUiThread {
                        //构建数据源的消息体
                        val messageEntity = MessageEntity(
                            EMClient.getInstance().currentUser,
                            dataBinding.liveChatRoomInputEt.text.toString()
                        )
                        messageList.add(messageEntity)
                        messageAdapter.notifyDataSetChanged()
                        dataBinding.liveChatRoomInputEt.text.clear()
                        dataBinding.liveChatRoomRv.scrollToPosition(messageList.size - 1)
                        dataBinding.liveChatRoomLayoutLl.visibility = View.GONE
                    }
                }

                override fun onError(code: Int, error: String?) {
                    //发送消息失败
                    Log.i("TagA", "发送消息失败:$error,$code")
                }
            })
        }

        dataBinding.liveCartIv.setOnClickListener {
            val intent = Intent(this, ShopActivity::class.java)
            startActivity(intent)
        }
    }

    //初始化聊天室
    private fun initChatRoom() {
        //聊天室添加监听器2种,一个是接收消息的监听器,另一个是进入聊天室的监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener)
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.CHAT_ROOM_ID, object : EMValueCallBack<EMChatRoom> {
            override fun onSuccess(value: EMChatRoom?) {
                Log.i("TagA", "加入聊天室成功")
            }

            override fun onError(error: Int, errorMsg: String?) {
                Log.i("TagA", "加入聊天室失败:$error,$errorMsg")
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.CHAT_ROOM_ID)
        EMClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomChangeListener)
        EMClient.getInstance().chatManager().removeMessageListener(messageListener)
    }

    private val chatRoomChangeListener = object : EMChatRoomChangeListener {
        override fun onChatRoomDestroyed(roomId: String?, roomName: String?) {
        }

        override fun onMemberJoined(roomId: String?, participant: String?) {
            runOnUiThread {
                val messageEntity = MessageEntity(
                    "系统",
                    "${participant}加入直播间"
                )
                messageList.add(messageEntity)
                messageAdapter.notifyDataSetChanged()
            }
        }

        override fun onMemberExited(roomId: String?, roomName: String?, participant: String?) {
            runOnUiThread {
                val messageEntity = MessageEntity(
                    "系统",
                    "${participant}退出直播间"
                )
                messageList.add(messageEntity)
                messageAdapter.notifyDataSetChanged()
            }
        }

        override fun onRemovedFromChatRoom(reason: Int, roomId: String?, roomName: String?, participant: String?) {
        }

        override fun onMuteListAdded(chatRoomId: String?, mutes: MutableList<String>?, expireTime: Long) {
        }

        override fun onMuteListRemoved(chatRoomId: String?, mutes: MutableList<String>?) {
        }

        override fun onWhiteListAdded(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onWhiteListRemoved(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onAllMemberMuteStateChanged(chatRoomId: String?, isMuted: Boolean) {
        }

        override fun onAdminAdded(chatRoomId: String?, admin: String?) {
        }

        override fun onAdminRemoved(chatRoomId: String?, admin: String?) {
        }

        override fun onOwnerChanged(chatRoomId: String?, newOwner: String?, oldOwner: String?) {
        }

        override fun onAnnouncementChanged(chatRoomId: String?, announcement: String?) {
        }
    }

    private val messageListener = EMMessageListener {
        runOnUiThread {
            it.forEach {
                val messageEntity = MessageEntity(
                    it.userName,
                    (it.body as EMTextMessageBody).message
                )
                messageList.add(messageEntity)
                messageAdapter.notifyDataSetChanged()
            }
        }
    }

    //发送礼物的方法
    private fun sendGift() {

        if (giftBean == null) {
            ToastUtils.showLong("还没有选择礼物")
            return
        }
        if (money.money < giftBean.price) {
            ToastUtils.showLong("用户余额不足,请充值")
            return
        }

        val newMoney = money.money - giftBean.price
        dataBinding.liveUserMoneyTv.text = "余额:${newMoney}抖币"

        money.money = newMoney
        viewModel.updateUserMoney(money)


        val giftAnimView = ImageView(this)
        val params = ConstraintLayout.LayoutParams(200, 200)
        giftAnimView.layoutParams = params

        dataBinding.liveRootCl.addView(giftAnimView)
        ImageUtils.loadImage(this, giftBean.giftpath, giftAnimView)

        val screenWidth = dataBinding.liveRootCl.measuredWidth
        val screenHeight = dataBinding.liveRootCl.measuredHeight

        val translationY =
            ObjectAnimator.ofFloat(
                giftAnimView,
                "translationY",
                screenHeight.toFloat(),
                (screenHeight / 3 * 2).toFloat(),
                (screenHeight / 2).toFloat()
            )

        val translationX =
            ObjectAnimator.ofFloat(
                giftAnimView,
                "translationX",
                (screenWidth / 2).toFloat(),
                (screenWidth / 3 * 2).toFloat(),
                (screenWidth / 2).toFloat(),
                (screenWidth / 3).toFloat(),
                (screenWidth / 2).toFloat()
            )

        val rotation = ObjectAnimator.ofFloat(giftAnimView, "rotation", 0f, 1800f)
        val scaleX = ObjectAnimator.ofFloat(giftAnimView, "scaleX", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val scaleY = ObjectAnimator.ofFloat(giftAnimView, "scaleY", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val alpha = ObjectAnimator.ofFloat(giftAnimView, "alpha", 0.1f, 0.5f, 1.0f, 0.5f, 0.1f)

        val animatorSet = AnimatorSet()
        animatorSet.duration = 3000
        animatorSet.interpolator = AccelerateDecelerateInterpolator()
        animatorSet.playTogether(translationX, translationY, rotation, scaleX, scaleY, alpha)
        animatorSet.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationStart(animation: Animator) {
                super.onAnimationStart(animation)
                dataBinding.liveGiftLayoutCl.visibility = View.GONE
            }

            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                dataBinding.liveRootCl.removeView(giftAnimView)
            }
        })
        animatorSet.start()
    }

    private fun sendDammu() {
        //获取弹幕内容
        val danmuString = dataBinding.liveDanmuInputEt.text.toString()
        if (TextUtils.isEmpty(danmuString)) {
            ToastUtils.showLong("请输入弹幕内容,不能为空")
            return
        }

        //清理弹幕
        dataBinding.liveDanmakuView.clear()
        dataBinding.liveDanmakuView.removeAllDanmakus(true)

        //构建弹幕实体
        val danmaku = danmukuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        danmaku.text = danmuString
        danmaku.textSize = 30f
        danmaku.textColor = Color.WHITE
        danmaku.padding = 10
        danmaku.time = 800

        //添加弹幕到View中
        dataBinding.liveDanmakuView.addDanmaku(danmaku)
        dataBinding.liveDanmakuView.start()

        //发送完毕后隐藏弹幕输入框和清空弹幕输入框中的内容
        dataBinding.liveDanmuInputEt.postDelayed({
            dataBinding.liveDanmuInputEt.text.clear()
            dataBinding.liveDanmuLayoutLl.visibility = View.GONE
        }, 300)
    }

    private lateinit var danmukuContext: DanmakuContext

    private fun initDanmuView() {
        //1.清空弹幕缓存
        dataBinding.liveDanmakuView.enableDanmakuDrawingCache(false)
        dataBinding.liveDanmakuView.clear()
        dataBinding.liveDanmakuView.removeAllDanmakus(true)

        //2.创建弹幕上下文
        danmukuContext = DanmakuContext.create()

        //3.准备弹幕
        dataBinding.liveDanmakuView.prepare(object : BaseDanmakuParser() {
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        }, danmukuContext)
    }

    override fun getLayoutId(): Int = R.layout.activity_live
}